package com.linshengjian.snowball.core.controller;

import com.linshengjian.snowball.core.BaseModel;
import com.linshengjian.snowball.core.IBaseService;
import com.linshengjian.snowball.core.exception.BusinessException;
import com.linshengjian.snowball.core.exception.SystemErrorException;
import com.linshengjian.snowball.core.page.PageData;
import com.linshengjian.snowball.core.page.PageParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;

public class BaseController<ID extends Serializable,M extends BaseModel<ID>, S extends IBaseService<M, ID>>{

    @Autowired
    private S service;

    @ApiOperation("根据ID 获取详情")
    @GetMapping("{id}")
    public M get(
            @ApiParam("主键") @PathVariable ID id
    ) throws SystemErrorException {
        return service.get(id);
    }

    @ApiOperation("分页查询")
    @GetMapping()
    public PageData<M> list(
            @ApiParam("关键字") String keywords,
            PageParam pageReq
    ) throws Exception {
        if (StringUtils.isEmpty(keywords)) {
            return service.list(pageReq);
        } else {
            return service.list(keywords, pageReq);
        }
    }

    @ApiOperation("新增")
    @PostMapping
    public M add(M model) throws SystemErrorException, BusinessException {
        return service.add(model);
    }

    @ApiOperation("修改")
    @PutMapping
    public M update(M model) throws SystemErrorException, BusinessException {
        return service.update(model);
    }

    @ApiOperation("删除")
    @DeleteMapping("{id}")
    public void delete(@PathVariable ID id) throws BusinessException, SystemErrorException {
        service.delete(id);
    }
}
